
var common = require("../../utils/Conmon.js");
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    offsetRecord: { 'index': -1, 'startX': 0, 'offset': 0, 'direction': null }, // 偏移记录
    deleteButtonWidth: 115, // 删除按钮的宽度(rpx)
    pixelScale: 1,
    selectAll: false,
    scrollY: true,
    list: [],
    cartCount: 0,
    cartMoney: '0.00',
    showIcon: 0
  },
  actShow: function (e) {
    var id = e.currentTarget.id, list = this.data.list;
    for (var i = 0, len = list.length; i < len; ++i) {
      if (list[i].id == id) {
        list[i].open = !list[i].open;
      }
    }
    this.setData({
      list: list
    })
  },
  //清空某店铺购物车
  delAll: function (e) {
    var shopid = e.currentTarget.id;
    var that = this;
    wx.showModal({
      content: "确定要删除该店铺所有商品吗？",
      showCancel: true,
      confirmText: "确定",
      success: function (res) {
        if (res.confirm) {          
          wx.showToast({
            title: '加载中...',
            icon: 'loading'
          })
          var url = "/mobile/api/ShopCart/DeleteUserCart";
          var data = { custId: app.globalData.custID, userId: wx.getStorageSync('UserInfo').UserID };
          if (shopid > 0) {
            url = "/mobile/api/ShopCart/DeleteUnionStoreShopCart";
            data = { custId: app.globalData.custID, userId: wx.getStorageSync('UserInfo').UserID, shopId: shopid };
          }
          wx.request({
            url: app.globalData.apiurl + url,
            data: data,
            method: 'GET',
            header: {
              'X_ManuName': app.globalData.manuName
            },
            success: function (res) {
              wx.hideToast();
              if (res.data.code == 1200) {
                var list = that.data.list;
                for (var i = 0, len = list.length; i < len; i++) {
                  if (list[i].ShopId == shopid) {
                    list.splice(i, 1);
                    break;
                  }
                }
                if (list.length <= 0) {
                  that.setData({ showIcon: 1 });
                }
                that.setData({ list: list, offsetRecord: null });
                statisticsMoney(that);
              } else {
                wx.showModal({
                  content: "操作失败",
                  showCancel: false,
                  confirmText: "确定",
                })
              }
            }
          })
        }
      }
    })
  },
  seleceItem: function (e) {
    var selectAll = this.data.selectAll;
    var id = e.currentTarget.id, list = this.data.list;
    var selectshop = 0;
    for (var i = 0, len = list.length; i < len; ++i) {
      var selectcount = 0;
      for (var j = 0, lenth = list[i].Cart.length; j < lenth; ++j) {
        if (list[i].Cart[j].CartID == id) {
          list[i].Cart[j].selected = !list[i].Cart[j].selected;
        }
        if (list[i].Cart[j].selected == true) {
          selectcount++;
        }
      }
      if (selectcount == list[i].Cart.length) {
        list[i].selected = true;
      } else {
        list[i].selected = false;
      }
      if (list[i].selected == true) {
        selectshop++;
      }
    }
    if (selectshop == list.length) {
      selectAll = true;
    } else {
      selectAll = false;
    }
    this.setData({
      list: list,
      selectAll: selectAll
    });
    //重新计算金额
    statisticsMoney(this);
  },
  //店铺全选
  selectShop: function (e) {
    var shopid = e.target.dataset.shopid, list = this.data.list;
    var selectAll = false;
    var selectcount = 0;
    for (var i = 0, len = list.length; i < len; ++i) {
      if (list[i].ShopId == shopid) {
        //全选店铺里的商品
        for (var j = 0, lenth = list[i].Cart.length; j < lenth; ++j) {
          list[i].Cart[j].selected = !list[i].selected;
        }
        list[i].selected = !list[i].selected;
      }
      if (list[i].selected == true) {
        selectcount++;
      }
    }
    if (selectcount == list.length) {
      selectAll = true;
    }
    this.setData({
      list: list,
      selectAll: selectAll
    });
    //重新计算金额
    statisticsMoney(this);
  },
  //全选
  selectAll: function (e) {
    var selectAll = this.data.selectAll;
    var list = this.data.list;
    for (var i = 0, len = list.length; i < len; i++) {
      list[i].selected = !selectAll;
      for (var j = 0, lenth = list[i].Cart.length; j < lenth; ++j) {
        list[i].Cart[j].selected = !selectAll;
      }
    }
    this.setData({
      selectAll: !selectAll,
      list: list
    });
    //重新计算金额
    statisticsMoney(this);
  },
  //减少数量
  onsub: function (e) {
    var id = e.currentTarget.id, list = this.data.list;
    var shopid = e.target.dataset.shopid;
    var goodsid = 0, buynum = 0;
    for (var i = 0, len = list.length; i < len; i++) {
      if (list[i].ShopId == shopid) {
        for (var j = 0, lenth = list[i].Cart.length; j < lenth; ++j) {
          if (list[i].Cart[j].CartID == id) {
            goodsid = list[i].Cart[j].GoodsID;
            buynum = list[i].Cart[j].BuyNum - 1;
            if (buynum < 1) {
              buynum = 1;
            }
            list[i].Cart[j].BuyNum = buynum;
          }
        }
      }
    }
    this.setData({
      list: list
    })
    changeNum(this, id, goodsid, buynum, shopid);
  },
  //增加数量
  onplus: function (e) {
    var id = e.currentTarget.id, list = this.data.list;
    var shopid = e.target.dataset.shopid;
    var goodsid = 0, buynum = 0;
    for (var i = 0, len = list.length; i < len; i++) {
      if (list[i].ShopId == shopid) {
        for (var j = 0, lenth = list[i].Cart.length; j < lenth; ++j) {
          if (list[i].Cart[j].CartID == id) {
            goodsid = list[i].Cart[j].GoodsID;
            buynum = list[i].Cart[j].BuyNum + 1;
            list[i].Cart[j].BuyNum = buynum;
          }
        }
      }
    }
    this.setData({
      list: list
    })
    changeNum(this, id, goodsid, buynum, shopid);
  },
  onblur: function (e) {
    var buynum = e.detail.value;
    if (buynum < 1)
      buynum = 1;
    var id = e.currentTarget.id, list = this.data.list;
    var shopid = e.target.dataset.shopid;
    var goodsid = 0;
    for (var i = 0, len = list.length; i < len; i++) {
      if (list[i].ShopId == shopid) {
        for (var j = 0, lenth = list[i].Cart.length; j < lenth; ++j) {
          if (list[i].Cart[j].CartID == id) {
            goodsid = list[i].Cart[j].GoodsID;
            list[i].Cart[j].BuyNum = buynum;
          }
        }
      }
    }
    this.setData({
      list: list
    })
    changeNum(this, id, goodsid, buynum, shopid);
  },
  //去结算
  gobuy: function (e) {
    var list = this.data.list;
    var selectlist = [];
    for (var i = 0, len = list.length; i < len; i++) {
      for (var j = 0, lenth = list[i].Cart.length; j < lenth; ++j) {
        var cart = list[i].Cart[j];
        var goods = {};
        if (cart.selected) {
          goods.CartID = cart.CartID;
          goods.ProductID = cart.ProductID;
          goods.GoodsID = cart.GoodsID;
          goods.ShopId = cart.ShopId;
          goods.CustID = cart.CustID;
          goods.BuyNum = cart.BuyNum;
          selectlist.push(goods);
        }
      }
    }
    if (selectlist.length <= 0) {
      wx.showModal({
        content: "请勾上要购买的商品",
        showCancel: false,
        confirmText: "确定"
      })
      return;
    }
    
    //将购物车选中项缓存起来
    wx.setStorageSync('Winmobi4MallSelectedShopCart', selectlist);

    wx.navigateTo({
      url: '/pages/submitOrder/submitOrder',
    })
  },

  /**
     * 表格cell触摸开始事件
     */
  onTableCellTouchStart: function (event) {
    if (event.changedTouches.length != 1) return;
    let index = event.currentTarget.dataset.index;
    let x = event.changedTouches[0].clientX;
    let offset = 0;
    if (this.data.offsetRecord != null && this.data.offsetRecord.index == index) {
      offset = this.data.offsetRecord.offset;
    }
    this.setData({ offsetRecord: { 'index': index, 'startX': x, 'offset': offset, 'direction': null } });
  },

  /**
   * 表格cell触摸移动事件
   */
  onTableCellTouchMove: function (event) {
    if (event.changedTouches.length != 1) return;
    let index = event.currentTarget.dataset.index;
    let record = this.data.offsetRecord;
    if (record == null || index != Reflect.get(record, 'index')) {
      return;
    }
    let clientX = event.changedTouches[0].clientX;
    let startX = Reflect.get(record, 'startX');

    if (Reflect.get(record, 'direction') == undefined) {
      // 记录手势是左滑还是右滑
      let direction = startX >= clientX ? 'left' : 'right';
      Reflect.set(record, 'direction', direction);
    }
    if (Reflect.get(record, 'direction') == 'left') { // 👈滑动
      record.offset = Math.min((startX - clientX) * this.data.pixelScale, this.data.deleteButtonWidth);
    } else { // 👉滑动
      if (record.offset > 0) {
        record.offset = Math.max(this.data.deleteButtonWidth - Math.abs(clientX - startX) * this.data.pixelScale, 0);
      } else {
        record = null;
      }
    }
    this.setData({ offsetRecord: record });
  },

  /**
   * 表格cell触摸结束事件
   */
  onTableCellTouchEnd: function (event) {
    if (event.changedTouches.length != 1) return;
    let index = event.currentTarget.dataset.index;
    let record = this.data.offsetRecord;

    if (record != null && index == Reflect.get(record, 'index')) {
      let offset = Reflect.get(record, 'offset');
      if (offset >= this.data.deleteButtonWidth / 2) {
        Reflect.set(record, 'offset', this.data.deleteButtonWidth);
      } else {
        record = null;
      }
      this.setData({ offsetRecord: record });
    }
  },

  /**
   * 表格cell删除按钮点击事件
   */
  onDeleteButtonTapped: function (e) {
    var cartId = e.currentTarget.id;
    var shopId = e.target.dataset.shopid;
    var that = this;
    wx.showModal({
      content: `确定要删除吗？`,
      showCancel: true,
      success: (res) => {
        if (!res.confirm)
          return;

        wx.showToast({
          title: '加载中...',
          icon: 'loading'
        })
        wx.request({
          url: app.globalData.apiurl + '/mobile/api/ShopCart/Delete',
          data: { custId: app.globalData.custID, cartIds: cartId, shopId: shopId },
          method: 'GET',
          header: {
            'X_ManuName': app.globalData.manuName
          },
          success: function (res) {
            wx.hideToast();
            if (res.data.code == 1200) {
              var list = that.data.list;
              for (var i = 0, len = list.length; i < len; i++) {
                if (list[i].ShopId == shopId) {
                  for (var j = 0, lenth = list[i].Cart.length; j < lenth; ++j) {
                    if (list[i].Cart[j].CartID == cartId) {
                      list[i].Cart.splice(j, 1);
                      break;
                    }
                  }
                  if (list[i].Cart.length <= 0) {
                    list.splice(i, 1);
                  }
                  break;
                }
              }
              if (list.length <= 0) {
                that.setData({ showIcon: 1 });
              }
              that.setData({ list: list, offsetRecord: null });
              statisticsMoney(that);
            } else {
              wx.showModal({
                content: "操作失败",
                showCancel: false,
                confirmText: "确定",
              })
            }
          }
        })
      }
    });
  },




  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // var that = this;
    // loadCart(that);
   
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    that.setData({
      selectAll: false,
      showIcon:0
    });

    loadCart(that);
    common.pageInit(function () {
    });

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
})

function loadCart(that) {
  wx.showLoading({
    title: '加载中...',
    mask: true
  });
  wx.request({
    url: app.globalData.apiurl + '/mobile/api/ShopCart/GetListWechat',
    data: { custId: app.globalData.custID, userId: wx.getStorageSync('UserInfo').UserID },
    method: 'GET',
    header: {
      // 'X_ManuName': app.globalData.manuName
    },
    success: function (res) {
      wx.hideLoading();
      if (res.data.code == 1200) {
        var result = res.data.content;
        that.setData({
          list: result.UnionCart,
          cartCount: result.CartCount,
          cartMoney: result.CartMoney.toFixed(2)
        });
        if (result.UnionCart == null || result.UnionCart.length <= 0) {
          that.setData({ showIcon: 1 });
        }

        statisticsMoney(that);
      } else {
        wx.hideLoading();
        console.log('加载失败');
      }
    }
  })
}

//重新计算总金额 总数量
function statisticsMoney(that) {
  var amount = 0.00;
  var cartnum = 0;
  var list = that.data.list;
  if (list) {
    for (var i = 0, len = list.length; i < len; i++) {
      for (var j = 0, lenth = list[i].Cart.length; j < lenth; j++) {
        var cart = list[i].Cart[j];
        if (cart.selected) {
          amount += cart.CurrentPrice * cart.BuyNum;
          cartnum++;
        }
      }
    }
  }
  that.setData({
    cartCount: cartnum,
    cartMoney: amount.toFixed(2)
  })
}

//修改数量
function changeNum(that, cartId, goodsId, buynum, shopId) {
  var data = { CustID: app.globalData.custID, UserID: wx.getStorageSync('UserInfo').UserID, CartID: cartId, GoodsID: goodsId, BuyNum: buynum, ShopId: shopId };
  wx.request({
    url: app.globalData.apiurl + '/mobile/api/ShopCart/UpdateShopCart',
    data: JSON.stringify(data),
    header: {
      'X_ManuName': app.globalData.manuName
    },
    method: 'POST',
    success: function (res) {
      if (res.data.code == 1200) {
        statisticsMoney(that);
      } else {
        wx.showModal({
          content: res.data.msg,
          showCancel: false,
          confirmText: "确定",
        })
      }
    }
  })
}